package sa.com.sure.ejtimaa.common;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

import sa.com.sure.ejtimaa.R;

import android.content.Context;
import android.content.DialogInterface;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;


public class OpenDialogFile extends LinearLayout {

	  public OpenDialogFile(Context context) {
	    super(context);

	    init(context);
	  }

	  public OpenDialogFile(Context context, AttributeSet attrs) {
	    super(context, attrs);

	    init(context);
	  }

	  public static OpenDialogFile Instance = new OpenDialogFile(AppHelper.getAppContext());
	  
	  private void setItemLayout(View view) {
		  LayoutParams lay = new LinearLayout.LayoutParams(
			        ViewGroup.LayoutParams.FILL_PARENT,
			        ViewGroup.LayoutParams.WRAP_CONTENT, 0.0F);
		 lay.gravity = Gravity.RIGHT;
	     view.setLayoutParams(lay);
	  }

	 
	private void setListLayout(View view) {
		LayoutParams lay = new LinearLayout.LayoutParams(
		        ViewGroup.LayoutParams.FILL_PARENT,
		        ViewGroup.LayoutParams.FILL_PARENT, 0.0F);
		lay.gravity = Gravity.RIGHT;

	    view.setLayoutParams(lay);
	  }

	  private void init(Context context) {
	    setOrientation(LinearLayout.VERTICAL);
	    setListLayout(this);
	    
	    
	    _tvPath = new TextView(context);
	    setItemLayout(_tvPath);
	    _tvPath.setText("");

	    _etFile = new EditText(context);
	    setItemLayout(_etFile);
	    _etFile.setEnabled(false);
	    _etFile.setFocusable(false);

	    _FileList = new FileList(context);
	    setListLayout(_FileList);
	    _FileList.setPath("/");
	    _FileList.setFocusable(true);
	    _FileList.setOnPathChangedListener(_OnPathChanged);
	    _FileList.setOnFileSelected(_OnFileSelected);

	    addView(_tvPath);
	    addView(_etFile);
	    addView(_FileList);

	    setFocusable(true);
	    setFocusableInTouchMode(true);
	  }

	  private TextView _tvPath = null;
	  private EditText _etFile = null;
	  private FileList _FileList = null;

	  public String getPath() {
	    return _tvPath.getText().toString();
	  }

	  public String getFileName() {
	    return _etFile.getText().toString();
	  }

	  private OnPathChangedListener _OnPathChanged = new OnPathChangedListener() {
	    public void onChanged(String path) {
	      _tvPath.setText(path);
	      _etFile.setText("");
	    }
	  };

	  private OnFileSelectedListener _OnFileSelected = new OnFileSelectedListener() {
	    public void onSelected(String path, String fileName) {
	      _etFile.setText(fileName);
	    }
	  };
	  
	  public void ShowDialog(Context context ,  final OnFileSelectedListener _OnFileSelected, final OnPathChangedListener _OnCanceled){
		  
		   final OpenDialogFile openDialogFile = new OpenDialogFile(AppHelper.getAppContext());
		  
		    android.content.DialogInterface.OnClickListener OnPositiveClick = new DialogInterface.OnClickListener() {
	    	    public void onClick(DialogInterface dialog, int which) {
	    	      if (_OnFileSelected != null) {
	    	        _OnFileSelected.onSelected(openDialogFile.getPath(),
	    	        		openDialogFile.getFileName());
	    	      }
	    	    }
	    	  };
	
	    	  android.content.DialogInterface.OnClickListener OnNegativeClick = new DialogInterface.OnClickListener() {
		    	    public void onClick(DialogInterface dialog, int which) {
		    	      if (_OnCanceled != null) {
		    	       // _OnCanceled.onNotify(OpenDialog.this);
		    	      }
		    	    }
		    	  };
   	  	 AppDialogs.Dialog(context,AppHelper.getAppContext().getString(R.string.SelectFile) , openDialogFile, OnPositiveClick, OnNegativeClick);		  
	  }

	}



	interface OnPathChangedListener {

	  public void onChanged(String path);

	}

	class FileList extends ListView {

	  public FileList(Context context, AttributeSet attrs, int defStyle) {
	    super(context, attrs, defStyle);

	    init(context);
	  }

	  public FileList(Context context, AttributeSet attrs) {
	    super(context, attrs);

	    init(context);
	  }

	  public FileList(Context context) {
	    super(context);

	    init(context);
	  }

	  private void init(Context context) {
	    _Context = context;
	  }
	  	  
	  
	  private Context _Context = null;
	  private ArrayList<String> _List = new ArrayList<String>();
	  private ArrayList<String> _FolderList = new ArrayList<String>();
	  private ArrayList<String> _FileList = new ArrayList<String>();

	  // Property
	  private String _Path = "";

	  // Event
	  private OnPathChangedListener _OnPathChangedListener = null;
	  private OnFileSelectedListener _OnFileSelectedListener = null;

	  private boolean openPath(String path) {
	    _FolderList.clear();
	    _FileList.clear();

	    File file = new File(path);
	    File[] files = file.listFiles();
	    if (files == null)
	    {
	      Helper.ShowToast(AppHelper.getAppContext().getString(R.string.NoFilesExists));
	      return false;
	    }
	    for (int i = 0; i < files.length; i++) {
	      if (files[i].isDirectory()) {
	        _FolderList.add("<" + files[i].getName() + ">");
	      } else {
	        _FileList.add(files[i].getName());
	      }
	    }

	    Collections.sort(_FolderList);
	    Collections.sort(_FileList);

	    _FolderList.add(0, "<..>");

	    return true;
	  }

	  private void updateAdapter() {
	    _List.clear();
	    _List.addAll(_FolderList);
	    _List.addAll(_FileList);

	    adapter _adapter = new adapter(_Context,_List.toArray(new String[_List.size()]));
	    setAdapter(_adapter);
	    setItemsCanFocus(true);
	  }

	  public void setPath(String value) {
	    if (value.length() == 0) {
	      value = "/";
	    } else {
	      String lastChar = value.substring(value.length() - 1,
	          value.length());
	      if (lastChar.matches("/") == false)
	        value = value + "/";
	    }

	    if (openPath(value)) {
	      _Path = value;
	      updateAdapter();
	      if (_OnPathChangedListener != null)
	        _OnPathChangedListener.onChanged(value);
	    }
	  }

	  public String getPath() {
	    return _Path;
	  }

	  public void setOnPathChangedListener(OnPathChangedListener value) {
	    _OnPathChangedListener = value;
	  }

	  public OnPathChangedListener getOnPathChangedListener() {
	    return _OnPathChangedListener;
	  }

	  public void setOnFileSelected(OnFileSelectedListener value) {
	    _OnFileSelectedListener = value;
	  }

	  public OnFileSelectedListener getOnFileSelected() {
	    return _OnFileSelectedListener;
	  }

	  public String DelteRight(String value, String border) {
	    String list[] = value.split(border);

	    String result = "";

	    for (int i = 0; i < list.length; i++) {
	      result = result + list[i] + border;
	    }

	    return result;
	  }

	  private String delteLastFolder(String value) {
	    String list[] = value.split("/");

	    String result = "";

	    for (int i = 0; i < list.length - 1; i++) {
	      result = result + list[i] + "/";
	    }

	    return result;
	  }

	  private String getRealPathName(String newPath) {
	    String path = newPath.substring(1, newPath.length() - 1);

	    if (path.matches("..")) {
	      return delteLastFolder(_Path);
	    } else {
	      return _Path + path + "/";
	    }
	  }
	  

	  public class adapter extends ArrayAdapter<String> {
			private final Context context;
			private final String[] values;
			
			public adapter(Context context, String[] values) {
				super(context, R.layout.opendialog_list_item, values);
				this.context = context;
				this.values = values;
			}

			@Override
			public View getView(final int position, View convertView, ViewGroup parent) {
				LayoutInflater inflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				View rowView = inflater.inflate(R.layout.opendialog_list_item, parent, false);
				TextView textView = (TextView) rowView.findViewById(R.id.tvItem);
				ImageView imageView = (ImageView) rowView.findViewById(R.id.ivItem);
				
				String s = values[position];
				textView.setText(s);
				if (s.matches("<.*>")) {
					imageView.setImageResource(R.drawable.folder);
				} else {
					imageView.setImageResource(R.drawable.file);
				}
				
				rowView.setClickable(true);
				rowView.setFocusable(true);
				rowView.setBackgroundResource(android.R.drawable.menuitem_background);
				
				rowView.setOnClickListener(new OnClickListener() {

			        public void onClick(View v) {
			  	      String fileName = getItemAtPosition(position).toString();
				      if (fileName.matches("<.*>")) {
				        setPath(getRealPathName(fileName));
				      } else {
				        if (_OnFileSelectedListener != null)
				          _OnFileSelectedListener.onSelected(_Path, fileName);
				      }
			        }

			    });
				
				return rowView;
			}
		}
	  
	}